import React, { useEffect } from "react";
import { Card, Form, Input, Button, message } from "antd";
import { useNavigate, useParams } from "react-router-dom";
import { save, getById, updateById } from "@/api/hosp/hospitalSet";

function AddOrUpdateHospital() {
	const navigate = useNavigate();
	const params = useParams();
	const [form] = Form.useForm();

	useEffect(() => {
		if (params.id) {
			const getData = async () => {
				const data = await getById(+(params.id as string));
				form.setFieldsValue(data);
			};
			getData();
		}
	}, []);

	const onFinish = async (values: any) => {
		if (params.id) {
			updateById({
				...values,
				id: params.id,
			});
		} else {
			await save(values);
		}

		message.success(`${params.id ? "修改" : "添加"}医院成功`);
		cancel();
	};

	const cancel = () => {
		navigate("/hosp/hospitalSet/list");
	};

	return (
		<Card>
			<Form
				form={form}
				name="basic"
				labelCol={{ span: 2 }}
				wrapperCol={{ span: 22 }}
				onFinish={onFinish}
			>
				<Form.Item
					label="医院名称"
					name="hosname"
					rules={[{ required: true, message: "请输入医院名称!" }]}
				>
					<Input />
				</Form.Item>

				<Form.Item
					label="医院编号"
					name="hoscode"
					rules={[{ required: true, message: "请输入医院编号!" }]}
				>
					<Input />
				</Form.Item>

				<Form.Item
					label="api基础路径"
					name="apiUrl"
					rules={[{ required: true, message: "请输入api基础路径!" }]}
				>
					<Input />
				</Form.Item>

				<Form.Item
					label="联系人姓名"
					name="contactsName"
					rules={[{ required: true, message: "请输入联系人姓名!" }]}
				>
					<Input />
				</Form.Item>

				<Form.Item
					label="联系人手机"
					name="contactsPhone"
					rules={[{ required: true, message: "请输入联系人手机!" }]}
				>
					<Input />
				</Form.Item>

				<Form.Item wrapperCol={{ offset: 2 }}>
					<Button type="primary" htmlType="submit" style={{ marginRight: 10 }}>
						保存
					</Button>
					<Button onClick={cancel}>返回</Button>
				</Form.Item>
			</Form>
		</Card>
	);
}

export default AddOrUpdateHospital;
